//
//  KTEleCheckboxTableCell.m
//  BoWuGuan
//
//  Created by 梁尚嘉 on 2016/11/4.
//  Copyright © 2016年 WUTOBE. All rights reserved.
//

#import "KTEleCheckboxTableCell.h"
#import "KTCheckbox.h"

#define kCheckboxBaseTag 200
@interface KTEleCheckboxTableCell () <KTCheckBoxProtocol>

@end

@implementation KTEleCheckboxTableCell
{
    NSMutableArray <KTCheckbox *>*_checkBoxes;
    NSUInteger _selectedIndex;
}

- (void)configure
{
    [super configure];
    _checkBoxes = [NSMutableArray array];
}


- (void)setTitles:(NSArray *)titles
{
    _titles = titles;
    for (NSInteger i = _titles.count - 1; i >= 0; i--) {

        KTCheckbox *box = [self checkBoxExistAtIndex:i];

        if (!box) {

            box             = [self checkBoxMaker];
            box.tag         = i + kCheckboxBaseTag;
            box.delegate    = self;

            [_checkBoxes addObject:box];
            [self.contentView addSubview:box];

            [box mas_makeConstraints:^(MASConstraintMaker *make) {

                if (i == _titles.count - 1) {
                    make.right.equalTo(@(SM_SIZE(-30)));
                }else {
                    make.right.equalTo([self checkBoxExistAtIndex:i+1].mas_left).offset(SM_SIZE(-50));
                }
                make.centerY.equalTo(self.contentView.mas_centerY);
            }];

        }
        box.title = _titles[i];
    }
}

- (KTCheckbox *)checkBoxExistAtIndex:(NSUInteger)index
{
    return [self viewWithTag:index+kCheckboxBaseTag];
}

- (KTCheckbox *)checkBoxMaker
{
    return [KTCheckbox new];
}

#pragma mark - KTCheckBoxProtocol

- (void)checkBox:(KTCheckbox *)checkbox didClick:(BOOL)isSelected
{
    _selectedIndex = [_checkBoxes indexOfObject:checkbox];
    for (KTCheckbox *box in _checkBoxes) {
        box.selected = false;
    }
    _checkBoxes[_selectedIndex].selected = true;
}


- (void)setSelectedIndex:(NSUInteger)selectedIndex
{
    _selectedIndex = _checkBoxes.count-1 - selectedIndex;
    for (KTCheckbox *box in _checkBoxes) {
        box.selected = false;
    }
    _checkBoxes[_selectedIndex].selected = true;
}

- (NSUInteger)selectedIndex
{
    return _checkBoxes.count-1 - _selectedIndex;
}

@end
